import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../models/chat_message.dart';
import '../services/silicon_api_service.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../models/model_info.dart';
import '../screens/settings_screen.dart';
import '../models/chat_session.dart';
import 'dart:convert';
import '../models/ai_role.dart';
import 'package:permission_handler/permission_handler.dart';
import '../services/speech_service.dart';
import '../widgets/sound_level_painter.dart';
import 'package:flutter_markdown/flutter_markdown.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:flutter/rendering.dart';

class ChatScreen extends StatefulWidget {
  final ChatSession? session;
  
  ChatScreen({this.session});
  
  @override
  _ChatScreenState createState() => _ChatScreenState();
}

class _ChatScreenState extends State<ChatScreen> {
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  final TextEditingController _messageController = TextEditingController();
  late ChatSession _currentSession;
  List<ChatSession> _sessions = [];
  late SiliconApiService _apiService;
  late String _currentModel;
  bool _isWaiting = false;
  String _thinkingContent = '';
  final SpeechService _speechService = SpeechService();
  bool _isInitialized = false;
  double _soundLevel = 0.0;
  bool _isVoiceMode = false;
  bool _hasPermission = false;
  bool _isListening = false;

  @override
  void initState() {
    super.initState();
    _loadSessions();
    _currentSession = widget.session ?? 
        ChatSession(
          id: DateTime.now().millisecondsSinceEpoch.toString(),
          createdAt: DateTime.now(),
        );
    _initializeWithPermissions();
    _loadSettings();
  }

  Future<void> _loadSessions() async {
    final prefs = await SharedPreferences.getInstance();
    final sessionsJson = prefs.getStringList('chat_sessions') ?? [];
    setState(() {
      _sessions = sessionsJson.map((json) => 
        ChatSession(
          id: jsonDecode(json)['id'],
          messages: (jsonDecode(json)['messages'] as List)
              .map((m) => ChatMessage.fromJson(m))
              .toList(),
          createdAt: DateTime.parse(jsonDecode(json)['createdAt']),
          title: jsonDecode(json)['title'] ?? '',
        )).toList();
      
      // 按时间倒序排序
      _sessions.sort((a, b) => b.createdAt.compareTo(a.createdAt));
      
      // 如果是从历史记录打开的会话，设置当前会话
      if (widget.session != null) {
        _currentSession = _sessions.firstWhere(
          (s) => s.id == widget.session!.id,
          orElse: () => widget.session!,
        );
      }
    });
  }

  Future<void> _saveSessions() async {
    final prefs = await SharedPreferences.getInstance();
    final sessionsJson = _sessions.map((session) => 
      jsonEncode({
        'id': session.id,
        'messages': session.messages.map((m) => m.toJson()).toList(),
        'createdAt': session.createdAt.toIso8601String(),
        'title': session.title,
      })
    ).toList();
    await prefs.setStringList('chat_sessions', sessionsJson);
  }

  void _createNewSession() {
    final newSession = ChatSession(
      id: DateTime.now().millisecondsSinceEpoch.toString(),
      createdAt: DateTime.now(),
    );
    setState(() {
      _sessions.insert(0, newSession);
      _currentSession = newSession;
    });
    _saveSessions();
  }

  Future<void> _loadSettings() async {
    final prefs = await SharedPreferences.getInstance();
    setState(() {
      _currentModel = prefs.getString('selected_model') ?? ModelConfig.models[0].id;
      final apiKey = prefs.getString('api_key') ?? '';
      _apiService = SiliconApiService(apiKey: apiKey, model: _currentModel);
    });
  }

  Future<void> _generateTitle() async {
    // 只在第一次回答后生成标题
    if (_currentSession.messages.length != 2 || _currentSession.title.isNotEmpty) return;

    try {
      String prompt = '请为以下对话生成一个简短的总结性标题（20字以内）：\n';
      for (var msg in _currentSession.messages) {
        prompt += '${msg.isUser ? "用户" : "助手"}：${msg.content}\n';
      }

      String title = '';
      await for (final response in _apiService.sendMessageStream(prompt)) {
        title += response;
      }

      setState(() {
        _currentSession.title = title.trim();
      });
      _saveSessions();
    } catch (e) {
      print('生成标题失败: $e');
    }
  }

  Future<void> _deleteSession(ChatSession session) async {
    final confirmed = await showDialog<bool>(
      context: context,
      builder: (context) => AlertDialog(
        title: Text('删除对话'),
        content: Text('确定要删除这个对话吗？'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context, false),
            child: Text('取消'),
          ),
          TextButton(
            onPressed: () => Navigator.pop(context, true),
            child: Text('删除'),
            style: TextButton.styleFrom(foregroundColor: Colors.red),
          ),
        ],
      ),
    );

    if (confirmed == true) {
      setState(() {
        _sessions.remove(session);
        if (session.id == _currentSession.id) {
          _currentSession = ChatSession(
            id: DateTime.now().millisecondsSinceEpoch.toString(),
            createdAt: DateTime.now(),
          );
          _sessions.add(_currentSession);
        }
      });
      await _saveSessions();
    }
  }

  Widget _buildMessage(ChatMessage message) {
    if (!message.isUser && message.content.isEmpty && _isWaiting) {
      return Row(
        children: [
          Text(
            '...',
            style: TextStyle(
              fontSize: 16,
              color: Colors.grey[600],
            ),
          ),
          if (_thinkingContent.isNotEmpty)
            Padding(
              padding: const EdgeInsets.only(left: 8.0),
              child: Text(
                _thinkingContent,
                style: TextStyle(
                  fontSize: 12,
                  color: Colors.grey[400],
                  fontStyle: FontStyle.italic,
                ),
              ),
            ),
        ],
      );
    }

    return GestureDetector(
      onLongPress: () {
        showModalBottomSheet(
          context: context,
          builder: (context) => Container(
            height: 120,
            child: Column(
              children: [
                ListTile(
                  leading: Icon(Icons.content_copy),
                  title: Text('复制文本'),
                  onTap: () {
                    Clipboard.setData(ClipboardData(text: message.content));
                    Navigator.pop(context);
                    ScaffoldMessenger.of(context).showSnackBar(
                      SnackBar(content: Text('已复制到剪贴板')),
                    );
                  },
                ),
                ListTile(
                  leading: Icon(Icons.volume_up),
                  title: Text('语音播报'),
                  onTap: () async {
                    Navigator.pop(context);
                    await _speechService.speak(message.content);
                  },
                ),
              ],
            ),
          ),
        );
      },
      child: message.isUser
          ? Text(
              message.content,
              style: TextStyle(
                fontSize: 16,
                color: Colors.black,
              ),
            )
          : MarkdownBody(
              data: message.content,
              selectable: true,
              styleSheet: MarkdownStyleSheet(
                p: TextStyle(fontSize: 16, color: Colors.grey[800]),
                code: TextStyle(
                  fontSize: 14,
                  backgroundColor: Colors.grey[200],
                  fontFamily: 'monospace',
                ),
                codeblockDecoration: BoxDecoration(
                  color: Colors.grey[200],
                  borderRadius: BorderRadius.circular(4),
                ),
              ),
              onTapLink: (text, href, title) async {
                if (href != null) {
                  final url = Uri.parse(href);
                  if (await canLaunchUrl(url)) {
                    await launchUrl(url);
                  }
                }
              },
            ),
    );
  }

  Future<void> _initializeWithPermissions() async {
    // 请求麦克风权限
    final status = await Permission.microphone.request();
    if (status.isGranted) {
      setState(() {
        _hasPermission = true;
      });
      // 初始化语音服务
      await _speechService.initialize();
      setState(() {
        _isInitialized = true;
      });
    } else {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('需要麦克风权限才能使用语音功能')),
      );
    }
  }

  void _startVoiceInput() async {
    if (!_hasPermission) {
      final status = await Permission.microphone.request();
      if (!status.isGranted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('需要麦克风权限才能使用语音功能')),
        );
        return;
      }
      setState(() {
        _hasPermission = true;
      });
    }

    if (_isInitialized && _hasPermission) {
      try {
        setState(() {
          _isListening = true;
        });
        
        _speechService.onSoundLevelChange = (level) {
          setState(() {
            _soundLevel = level;
          });
        };
        
        await _speechService.startListening((text) {
          print('识别到的文本: $text');
          if (text.isNotEmpty) {
            setState(() {
              _messageController.text = text;
              _isListening = false;
            });
            _sendMessage();
          }
        });
      } catch (e) {
        print('启动语音输入失败: $e');
        setState(() {
          _isListening = false;
        });
      }
    }
  }

  void _stopVoiceInput() async {
    await _speechService.stopListening();
    setState(() {
      _isListening = false;
      _soundLevel = 0.0;
    });
  }

  void _sendMessage() async {
    if (_messageController.text.trim().isEmpty) return;

    final userMessage = _messageController.text;
    print('发送用户消息: $userMessage');

    setState(() {
      _currentSession.addMessage(ChatMessage(
        content: userMessage,
        isUser: true,
        timestamp: DateTime.now(),
      ));
      _isWaiting = true;
      _thinkingContent = '';
    });
    _messageController.clear();

    try {
      final aiMessage = ChatMessage(
        content: '',
        isUser: false,
        timestamp: DateTime.now(),
      );
      setState(() {
        _currentSession.addMessage(aiMessage);
      });

      String accumulatedResponse = '';
      print('开始接收AI响应...');
      
      await for (final response in _apiService.sendMessageStream(
        userMessage,
        chatHistory: _currentSession.messages.sublist(0, _currentSession.messages.length - 1),
      )) {
        if (response.startsWith('[think]')) {
          print('思考内容: ${response.substring(7)}');
          setState(() {
            _thinkingContent = response.substring(7);
          });
          continue;
        }
        
        accumulatedResponse += response;
        // print('收到片段: $response');
        // print('当前累积响应: $accumulatedResponse');
        
        setState(() {
          _currentSession.messages.last = ChatMessage(
            content: accumulatedResponse,
            isUser: false,
            timestamp: aiMessage.timestamp,
          );
        });
      }
      
      print('AI响应完成，总长度: ${accumulatedResponse.length}');
      
      // 确保在完整响应收到后再进行语音播报
      if (accumulatedResponse.isNotEmpty) {
        print('准备语音播报...');
        await Future.delayed(Duration(milliseconds: 500)); // 短暂延迟确保UI更新
        await _speechService.speak(accumulatedResponse);
        print('语音播报完成');
      }

    } catch (e) {
      print('发送消息失败: $e');
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('发送消息失败: $e')),
      );
      if (_currentSession.messages.last.content.isEmpty) {
        setState(() {
          _currentSession.messages.removeLast();
        });
      }
    } finally {
      setState(() {
        _isWaiting = false;
        _thinkingContent = '';
      });
      _saveSessions();
      await _generateTitle();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: _scaffoldKey,
      drawer: Drawer(
        child: Column(
          children: [
            DrawerHeader(
              child: Text(
                '聊天记录',
                style: Theme.of(context).textTheme.headlineSmall,
              ),
            ),
            Expanded(
              child: ListView.builder(
                itemCount: _sessions.length,
                itemBuilder: (context, index) {
                  final session = _sessions[index];
                  return ListTile(
                    title: Text(session.displayTitle),
                    subtitle: Text(
                      session.createdAt.toString().substring(0, 16),
                    ),
                    selected: session.id == _currentSession.id,
                    onTap: () {
                      setState(() {
                        _currentSession = session;
                      });
                      Navigator.pop(context);
                    },
                    onLongPress: () => _deleteSession(session),
                  );
                },
              ),
            ),
            ListTile(
              leading: Icon(Icons.settings),
              title: Text('设置'),
              onTap: () async {
                Navigator.pop(context);
                await Navigator.push(
                  context,
                  MaterialPageRoute(builder: (context) => SettingsScreen()),
                );
                _loadSettings();
              },
            ),
          ],
        ),
      ),
      appBar: AppBar(
        title: Text(_currentSession.displayTitle),
        leading: Builder(
          builder: (context) => IconButton(
            icon: Icon(Icons.menu),
            onPressed: () => Scaffold.of(context).openDrawer(),
          ),
        ),
        actions: [
          IconButton(
            icon: Icon(Icons.add),
            onPressed: _createNewSession,
          ),
        ],
      ),
      body: Stack(
        children: [
          Column(
            children: [
              Expanded(
                child: ListView.builder(
                  reverse: true,
                  itemCount: _currentSession.messages.length,
                  itemBuilder: (context, index) {
                    final message = _currentSession.messages[_currentSession.messages.length - 1 - index];
                    return _buildMessageBubble(message);
                  },
                ),
              ),
              _buildInputArea(),
            ],
          ),
          _buildVoiceIndicator(),
        ],
      ),
    );
  }

  Widget _buildMessageBubble(ChatMessage message) {
    return Align(
      alignment: message.isUser ? Alignment.centerRight : Alignment.centerLeft,
      child: Container(
        margin: EdgeInsets.all(8.0),
        padding: EdgeInsets.all(12.0),
        constraints: BoxConstraints(
          maxWidth: MediaQuery.of(context).size.width * 0.8,
        ),
        decoration: BoxDecoration(
          color: message.isUser ? Colors.blue : Colors.grey[300],
          borderRadius: BorderRadius.circular(12.0),
        ),
        child: _buildMessage(message),
      ),
    );
  }

  Widget _buildInputArea() {
    return Container(
      padding: EdgeInsets.all(8.0),
      child: Row(
        children: [
          IconButton(
            icon: Icon(_isVoiceMode ? Icons.keyboard : Icons.mic),
            onPressed: () {
              setState(() {
                _isVoiceMode = !_isVoiceMode;
              });
            },
          ),
          Expanded(
            child: _isVoiceMode
              ? GestureDetector(
                  onLongPressStart: (_) => _startVoiceInput(),
                  onLongPressEnd: (_) => _stopVoiceInput(),
                  child: Container(
                    height: 50,
                    decoration: BoxDecoration(
                      color: Colors.grey[200],
                      borderRadius: BorderRadius.circular(4),
                    ),
                    alignment: Alignment.center,
                    child: Text(
                      _isListening ? '松开发送' : '按住说话',
                      style: TextStyle(
                        color: Colors.grey[600],
                      ),
                    ),
                  ),
                )
              : TextField(
                  controller: _messageController,
                  decoration: InputDecoration(
                    hintText: '输入消息...',
                    border: OutlineInputBorder(),
                  ),
                ),
          ),
          if (!_isVoiceMode)
            IconButton(
              icon: Icon(Icons.send),
              onPressed: _sendMessage,
            ),
        ],
      ),
    );
  }

  Widget _buildVoiceIndicator() {
    if (!_isListening) return SizedBox.shrink();
    
    return Container(
      color: Colors.black54,
      child: Center(
        child: Container(
          width: 160,
          height: 160,
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(8),
          ),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Icon(
                Icons.mic,
                color: Colors.blue,
                size: 48,
              ),
              SizedBox(height: 16),
              Container(
                width: 100,
                height: 4,
                child: LinearProgressIndicator(
                  value: _soundLevel,
                  backgroundColor: Colors.grey[200],
                  valueColor: AlwaysStoppedAnimation<Color>(Colors.blue),
                ),
              ),
              SizedBox(height: 16),
              Text(
                '松开发送',
                style: TextStyle(
                  color: Colors.grey[600],
                  fontSize: 16,
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
} 